package week4.day23;

import java.io.*;
import java.util.Arrays;

/**
 * @Author fengzihao
 * @Date 2024-05-07 20:12
 */
public class SerializeAndDeserialize {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("a.txt"));
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("a.txt"));
        User user1 = new User(1,"zhangsan","12345678901",new Address("hubei","430000"));
        User user2 = new User(2,"lisi","12345678901",new Address("hubei","430000"));
        User[] users = new User[]{user1,user2};
        // 单个对象序列化和反序列化
        objectOutputStream.writeObject(user1);
        User user = (User)objectInputStream.readObject();
        System.out.println(user);
        // 数组的序列化和反序列化
        objectOutputStream.writeObject(users);
        User[] users1 = (User[]) objectInputStream.readObject();
        System.out.println(Arrays.toString(users1));

    }
}
class User implements Serializable {
    private int id;
    private String name;
    private String mobile;
    private Address address;

    public User(int id, String name, String mobile, Address address) {
        this.id = id;
        this.name = name;
        this.mobile = mobile;
        this.address = address;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", mobile='" + mobile + '\'' +
                ", address=" + address.toString() +
                '}';
    }
}
class Address implements Serializable{
    private String detail;
    private String code;

    public Address(String detail, String code) {
        this.detail = detail;
        this.code = code;
    }

    public String getDetail() {
        return detail;
    }

    public void setDetail(String detail) {
        this.detail = detail;
    }

    @Override
    public String toString() {
        return "Address{" +
                "detail='" + detail + '\'' +
                ", code='" + code + '\'' +
                '}';
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }
}
